/**
* @package Scribble
*/
$(document).ready(function() {

	// Determine which templates, if any, have been pre-selected
	var ts = $('#template-selection').val();
	var tsOuter = ts.split(',')[0];
	var tsInner = ts.split(',')[1];

	// Build selectors
	var templates = $.evalJSON($('#templates').val());
	for(var i=0; i<templates.outer.length; i++) {
		var li = addTemplateOption('outer', templates.outer[i]);
		if(templates.outer[i].name==tsOuter) {
			selectTemplate($(li), 'outer', templates.outer[i]);
		}
	}
	for(var i=0; i<templates.inner.length; i++) {
		var li = addTemplateOption('inner', templates.inner[i]);
		if(templates.inner[i].name==tsInner) {
			selectTemplate($(li), 'inner', templates.inner[i]);
		}
	}

	// If there are no available options in either selector then let the user know
	// we can't continue without them
	if($('#templates-outer li').size()==0) {
		$('#templates-outer').append($('<li><p class="no-templates">You have no outer templates to select!</p></li>'));
	}
});

/**
* Add an entry to the template listing.
*
* @param string Listing type (outer | inner)
* @param object Template data
* @return void
*/
function addTemplateOption(type, template) {
	var ul = $('#templates-'+type);
	var li = $('<li></li>');
	var a = $('<a href="#"></a>').appendTo(li);
	var p = $('<p></p>').text(template.shortdescription);

	li.data('template', template);

	a.text(template.title);
	a.html(a.html()+'<span>Used by <b>'+template.pagecount+'</b> pages</span>');
	a.bind("click", {type:type, template:template}, function(ev) {
		selectTemplate($(this).parents('li'), ev.data.type, ev.data.template);
		return false;
	});

	p.appendTo(a);

	ul.append(li);
	return li;
}

/**
* Flag the specified template as selected.
*
* @param HtmlElement <li> node holding the template
* @param string Template type (outer | inner)
* @param object Template data
* @return void
*/
function selectTemplate(el, type, template) {

	// Store the selections in the hidden form variable, ready for posting
	var t = $('#template-selection').val();
	var o = type=='outer' ? template.name : t.replace(/,.*$/, '');
	var i = type=='inner' ? template.name : t.replace(/^[^,]*,/, '');
	$('#template-selection').val(o+','+i);

	// Unhighlight any previously selected templates, and highlight the one
	// specified
	$('#templates-'+type+' li').removeClass('selected').find('p').slideUp('fast');
	$(el).addClass('selected').find('p').slideDown('fast');

	// If both an outer and inner template have been chosen, then enable the
	// selection button
	if($('#template-selection').val().match(/^.+,.+$/)) {
		$('#btn-select').removeClass('disabled').attr('disabled', false);
	}
	else {
		$('#btn-select').addClass('disabled').attr('disabled', true);
	}
	return false;
}